package com.xjm.service.serviceImpl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjm.config.AppConfig;
import com.xjm.constant.AppConst;
import com.xjm.entity.vo.Result;
import com.xjm.enums.XxApiEnum;
import com.xjm.excption.AppException;
import com.xjm.excption.NoLoginException;
import com.xjm.service.UserService;
import com.xjm.utils.RedisUtil;
import com.xjm.entity.model.UsersModel;
import com.xjm.mapper.UserMapper;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UsersModel> implements UserService {

    private final UserMapper userMapper;
    private final RedisUtil redisUtil;
    private final AppConfig appConfig;

    @Override
    public Result<Void> register(UsersModel userModel) {
        String nickname = userModel.getNickname();
        String password = userModel.getPassword();
        String phone = userModel.getPhone();
        String code = userModel.getCode();
        if (!ObjectUtil.isAllNotEmpty(nickname, password, phone, code)) {
            return Result.error("参数错误");
        }
        UsersModel user = userMapper.selectOne(new LambdaQueryWrapper<UsersModel>().eq(UsersModel::getPhone, phone));
        if (user != null) {
            return Result.error("手机号已被注册");
        }
        // 设置默认头像
        userModel.setAvatar(JSONUtil.parse(HttpUtil.get(XxApiEnum.HEAD.api)).getByPath("data", String.class));
        userMapper.insert(userModel);
        return Result.success("用户注册成功");
    }

    @Override
    public Result<JSON> login(UsersModel userModel) {
        JSON result = new JSONObject();
        String phone = userModel.getPhone();
        String password = userModel.getPassword();
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(password)) {
            return Result.error("账号或密码不能为空");
        }
        UsersModel user = userMapper.selectOne(new LambdaQueryWrapper<UsersModel>().eq(UsersModel::getPhone, phone));
        if (user == null) {
            return Result.error("账号不存在");
        }
        if (!user.getPassword().equals(password)) {
            return Result.error("密码错误");
        }
        String token = UUID.fastUUID().toString();
        redisUtil.set(AppConst.USER_TOKEN_PREFIX + token, user, 60 * 60 * 24);
        result.putByPath("token", token);
        result.putByPath("user", user);
        return Result.success(result);
    }

    @Override
    public Result<JSON> getQrStatus(String uuid) {
        JSON result = new JSONObject();
        Integer status = Optional.ofNullable((Integer) redisUtil.get(uuid)).orElse(4);
        result.putByPath("status", status);
        if (status == 2) {
            Integer usrId = (Integer) redisUtil.get(AppConst.QR_KEY + uuid);
            UsersModel user = userMapper.selectById(usrId);
            String token = UUID.fastUUID().toString();
            redisUtil.set(AppConst.USER_TOKEN_PREFIX + token, user, 60 * 60 * 24);
            result.putByPath("token", token);
            result.putByPath("user", user);
            return Result.success(result);
        }
        return Result.success(result);
    }

    @Override
    public Result<String> auth(String uuid, String token) {
        if (redisUtil.hasKey(uuid)) {
            // 移动端用户信息
            UsersModel user = (UsersModel) redisUtil.get(AppConst.USER_TOKEN_PREFIX + token);
            if (user == null) throw new NoLoginException("登录已过期，请重新登录");
            redisUtil.set(uuid, 1, redisUtil.getExpire(uuid));
            redisUtil.set(AppConst.QR_KEY + uuid, user.getId(), redisUtil.getExpire(uuid));
            return Result.success("登录成功");
        } else {
            return Result.error("二维码已过期");
        }
    }

    @Override
    public Result<Void> confirm(String uuid) {
        if (redisUtil.hasKey(uuid)) {
            Integer status = (Integer) redisUtil.get(uuid);
            if (status != 1) return Result.error("二维码已过期,请刷新重试");
            redisUtil.set(uuid, 2, redisUtil.getExpire(uuid));
            return Result.success("登录成功");
        } else {
            return Result.error("二维码已过期,请刷新重试");
        }
    }

    @Override
    public Result<Void> cancel(String uuid) {
        if (redisUtil.hasKey(uuid)) {
            redisUtil.set(uuid, 3, redisUtil.getExpire(uuid));
            return Result.success("取消成功");
        } else {
            return Result.error("二维码已过期,请刷新重试");
        }
    }

    @Override
    public String uploadAvatar(MultipartFile file) {
        //后缀
        try {
            String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.fastUUID() + suffix;
            file.transferTo(new File(appConfig.getSavePath() + fileName));
            return appConfig.getUrlMapping() + fileName;
        } catch (IOException e) {
            throw new AppException(e.getMessage());
        }
    }
}
